package stone;

import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.io.*;

public class CodeDialog extends Reader {
  private String buffer = null;
  private int pos = 0;

  public int read(@NotNull char[] cBuf, int off, int len) throws IOException {
    if (buffer == null) {
      var in = showDialog();
      if (in == null) {
        return -1;
      } else {
        print(in);
        buffer = in + "\n";
        pos = 0;
      }
    }
    var size = 0;
    var length = buffer.length();
    while (pos < length && size < len) {
      cBuf[off + size++] = buffer.charAt(pos++);
    }
    if (pos == length) {
      buffer = null;
    }
    return size;
  }

  protected void print(String s) {
    System.out.println(s);
  }

  public void close() throws IOException {

  }

  protected String showDialog() {
    var area = new JTextArea(20, 40);
    var pane = new JScrollPane(area);
    var result = JOptionPane
        .showOptionDialog(
            null, pane, "Input",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
            null, null, null);
    return result == JOptionPane.OK_CANCEL_OPTION ? area.getText() : null;
  }

  @NotNull
  @Contract(" -> new")
  public static Reader file() throws FileNotFoundException {
    var chooser = new JFileChooser();
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
      return new BufferedReader(new FileReader(chooser.getSelectedFile()));
    else throw new FileNotFoundException("no file specified");
  }
}
